package com.mcbbs.web.service.impl;

import com.mcbbs.web.entity.Users;
import com.mcbbs.web.mapper.UsersMapper;
import com.mcbbs.web.service.UsersService;
import com.mcbbs.web.util.SHA256;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("UsersService")
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;
    @Override
    public Users login(String username, String password) {
//        将所有的大写的字母转换成小写：好处：用户输入时可能会输入LengMou 而我们数据库中的用户名是lengmou这样从而兼容了用户的所有输入
        String s = username.toLowerCase();
        Users users = usersMapper.queryByName(s);
        if(users!=null){
//            判断用户输入的密码是否和数据库中加密后的密码是否相同
            boolean b = SHA256.isequalsPwd(password, users.getPassword());
            if(b){
//                密码相同返回用户实体
                return users;
            }
        }
        return null;
    }

    @Override
    public List<Users> getAllUsers() {

        return usersMapper.querysAll();
    }

    @Override
    public Users getUsersByName(String username) {
        return usersMapper.queryByName(username);
    }

    @Override
    public Users getUsersByID(int id) {
        return usersMapper.queryByID(id);
    }

    @Override
    public Users getUsersByEmail(String email) {

        return usersMapper.queryByEmail(email);
    }

    @Override
    public List<Users> search(Map<String, Object> map) {
        return usersMapper.search(map);
    }

//    修改密码
    @Override
    public int setUsersPwd(Users users) {
        Users usersID = usersMapper.queryByID(users.getId());
        if(usersID!=null){
            usersID.setPassword(users.getPassword());
            return usersMapper.updataUsers(usersID);
        }
//        找不到该用户
        return -1;
    }
//  设置邮箱
    @Override
    public int setUsersEmail(Users users) {
        Users usersID = usersMapper.queryByID(users.getId());
        if(usersID!=null){
            usersID.setEmail(users.getEmail());
            return usersMapper.updataUsers(usersID);
        }
//        找不到该用户
        return -1;
    }

    @Override
    public int regUsers(Users users) {
        Users usersName = usersMapper.queryByName(users.getUsername());
        if(usersName==null){
//            加密密码
            users.setPassword(SHA256.hashPwd(users.getPassword()));
            users.setRegdate(new Date().getTime());
            return usersMapper.addUsers(users);
        }
//        已经存在该用户名
        return -1;
    }
}
